package co.fitstart.admin.web.controller.credit.product;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.CreditCouponBatchService;
import co.fitstart.admin.service.CreditProductService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.coupon.CreditCouponBatch;
import co.fitstart.entity.credit.product.CreditProduct;
import co.fitstart.entity.credit.product.CreditProductType;


/**
 * 
 * @author houtao
 *
 */
@Controller
@RequestMapping("/credit-products")
@MenuSetting("menu-credit")
public class CreditProductController {
    
    private static final Logger logger = LoggerFactory.getLogger(CreditProductController.class);
    
    @Autowired
    private CreditProductService creditProductService;
    
    @Autowired
    private CreditCouponBatchService creditCouponBatchService;

    /**
     * List all products by page and type
     * 
     * @param type
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-credit-product-management")
    public ModelAndView list(@RequestParam(value = "type", required = false, defaultValue = "product") String type,
                             HttpServletRequest request,
                             Page page){
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-product-list");
        
        CreditProductType productType = CreditProductType.aliasOf(type);
        
        List<CreditProduct> products = creditProductService.list(productType, page);
        
        modelAndView.addObject("type", productType);
        modelAndView.addObject("products", products);
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    
    /**
     * View product
     * 
     * @param productId
     * @return
     */
    @RequestMapping(value = "/{productId}", method = RequestMethod.GET)
    @MenuSetting("submenu-credit-product-management")
    public ModelAndView view(@PathVariable("productId") Long productId){
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-product-view");
        
        CreditProduct product = creditProductService.load(CreditProduct.class, productId);
        
        modelAndView.addObject("product", product);
        
        return modelAndView;
    }
    
    /**
     * Display edit panel
     * 
     * @param productId
     * @return
     */
    @RequestMapping(value = "/{productId}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("productId") Long productId){
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-product-edit");
        
        CreditProduct product = creditProductService.load(CreditProduct.class, productId);
        
        modelAndView.addObject("product", product);
        
        return modelAndView;
    }
    
    /**
     * Do edit
     * 
     * @param product
     * @param inputTags
     * @return
     */
    @RequestMapping(value = "/{productId}", method = RequestMethod.PATCH)
    public @ResponseBody String onEdit(@Preloading("productId") CreditProduct product,
                                       @RequestParam(value = "inputTags", required = false) List<String> inputTags) {
        
        Result result = new Result();
        
        try {
            
        	if(null == inputTags || inputTags.isEmpty()) {
        		creditProductService.update(product.modify());
        	}else {
        		creditProductService.update(product.tags(inputTags).modify());
        	}
        	
            result.success().message("修改产品信息成功!");
            
        } catch(Exception e) {
            
            logger.error("#onEdit - ", e);
            
            result.fail().message("修改产品信息失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display edit cover panel
     * 
     * @param productId
     * @return
     */
    @RequestMapping(value = "/{productId}/cover", method = RequestMethod.GET)
    public ModelAndView editCover(@PathVariable("productId") Long productId){
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-product-cover-edit");
        
        modelAndView.addObject("productId", productId);
        
        return modelAndView;
    }
    
    /**
     * Do edit cover
     * 
     * @param productId
     * @param cover
     * @return
     */
    @RequestMapping(value = "/{productId}/cover", method = RequestMethod.PATCH)
    public @ResponseBody String onEditCover(@PathVariable("productId") Long productId,
                                            @RequestParam("cover") String cover){
        
        Result result = new Result();
        
        try {
        	
        	CreditProduct creditProduct = creditProductService.load(CreditProduct.class, productId);
            
        	creditProductService.update(creditProduct.editCover(cover));
            
            result.success().message("修改产品封面成功！");
            
        } catch(Exception e) {
            
            logger.error("#onEditCover - ", e);
            
            result.fail().message("修改产品封面失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/{type}-create",  method = RequestMethod.GET)
    @MenuSetting("submenu-credit-product-management")
    public ModelAndView create(@PathVariable("type") String type) {
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-" + type + "-create");
        
        List<CreditCouponBatch> creditCouponBatchs = creditCouponBatchService.list();
        modelAndView.addObject("creditCouponBatchs", creditCouponBatchs);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param creditProduct
     * @param login
     * @return
     */
    @RequestMapping( value = "", method = RequestMethod.POST)
    public @ResponseBody String onCreate(CreditProduct creditProduct,
    									 @Secure Login login,
    									 @RequestParam(value = "inputTags", required = true) List<String> inputTags) {
        
        Result result = new Result();
        
        try {
        	
        	creditProductService.create(creditProduct.tags(inputTags), login.getId());
        	
            result.success().message("新建商品成功！");
        
        } catch(Exception e) {
        	
        	logger.error("#onCreate - ", e);
            
            result.fail().message("新建商品失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display hide product panel
     * 
     * @param productId
     * @return
     */
    @RequestMapping(value = "/{productId}/disabled", method = RequestMethod.GET)
    public ModelAndView editDisabled(@PathVariable("productId") Long productId){
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-product-disabled");
        
        modelAndView.addObject("productId", productId);
        
        return modelAndView;
    }
    
    /**
     * Do hide product
     * 
     * @param product
     * @return
     */
    @RequestMapping(value = "/{productId}/disabled", method = RequestMethod.PATCH)
    public @ResponseBody String onEditDisabled(@Preloading("productId") CreditProduct product){
        
        Result result = new Result();
        
        try {
        	
        	creditProductService.update(product.editDisabled());
            
            result.success().message("修改产品显示状态成功！");
            
        } catch(Exception e) {
            
            logger.error("#onEditDisabled - ", e);
            
            result.fail().message("修改产品显示状态失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display buyable edit panel
     * 
     * @param productId
     * @return
     */
    @RequestMapping(value = "/{productId}/buyable", method = RequestMethod.GET)
    public ModelAndView editBuyable(@PathVariable("productId") Long productId){
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-product-buyable");
        
        modelAndView.addObject("productId", productId);
        
        return modelAndView;
    }
    
    /**
     * Do buy-close
     * 
     * @param product
     * @return
     */
    @RequestMapping(value = "/{productId}/buyable", method = RequestMethod.PATCH)
    public @ResponseBody String onEditBuyable(@Preloading("productId") CreditProduct product){
        
        Result result = new Result();
        
        try {
            
        	creditProductService.update(product.editBuyable());
        	
            result.success().message("修改产品购买状态成功！");
            
        } catch(Exception e) {
            
            logger.error("#onEditBuyable - ", e);
            
            result.fail().message("修改产品购买状态失败！");
            
        }

        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display stick article panel
     * 
     * @param productId
     * @param type
     * @return
     */
    @RequestMapping(value="/{productId}/stick", method=RequestMethod.GET)
    public ModelAndView stick(@PathVariable("productId") Long productId,
    						  @RequestParam(value = "type", required = false,
    						  defaultValue = "product") String type){
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-product-stick");
        
        modelAndView.addObject("productId", productId);
        modelAndView.addObject("type", type);
        
        return modelAndView;
    }

    /**
     * Do stick article
     * 
     * @param productId
     * @param type
     * @return
     */
    @RequestMapping(value="/{productId}/stick", method=RequestMethod.PATCH)
    public @ResponseBody String onStick(@PathVariable("productId") Long productId,
    									@RequestParam(value = "type", required = false,
    									defaultValue = "online") String type){
        
        Result result = new Result();
        
        try {
        	
        	CreditProduct creditProduct = creditProductService.load(CreditProduct.class, productId);
        	
        	CreditProductType productType = CreditProductType.aliasOf(type);
        	
        	creditProductService.stick(creditProduct, productType);
            
            result.success().message("置顶产品成功");
           
        } catch (Exception e) {
           
            logger.error("#onStick() error:", e);
           
            result.fail().message("置顶产品失败!");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * Display unstick article panel
     * 
     * @param productId
     * @param type
     * @return
     */
    @RequestMapping(value="/{productId}/unstick", method=RequestMethod.GET)
    public ModelAndView unstick(@PathVariable("productId") Long productId,
    							@RequestParam(value = "type",
    							required = false, defaultValue = "product") String type){
        
        ModelAndView modelAndView = new ModelAndView("credit/credit-product/credit-product-unstick");
        
        modelAndView.addObject("productId", productId);
        modelAndView.addObject("type", type);
        
        return modelAndView;
    }
    
    /**
     * Do unstick article
     * 
     * @param productId
     * @param type
     * @return
     */
    @RequestMapping(value="/{productId}/unstick", method=RequestMethod.PATCH)
    public @ResponseBody String onUnstick(@PathVariable("productId") Long productId,
    									  @RequestParam(value = "type", required = false, defaultValue = "product") String type){
        
        Result result = new Result();
        
        try {
        	
        	CreditProduct creditProduct = creditProductService.load(CreditProduct.class, productId);
        	
        	CreditProductType productType = CreditProductType.aliasOf(type);
        	
        	creditProductService.unStick(creditProduct, productType);
            
            result.success().message("取消置顶产品成功");
           
        } catch (Exception e) {
           
            logger.error("#onUnstick() error:", e);
           
            result.fail().message("取消置顶产品失败!");
        }
        
        return JsonUtils.toJsonString(result);
    }

}
